package cn.snowsoft.iot.module.cps.mqtt;

import okhttp3.Credentials;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.apache.commons.lang3.ObjectUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Map;

/**
 * 进行创建一个规则
 */
public class MqttRule {
    /**
     * 新增认证器
     *
     * @param map          数据构造
     * @param responseBody
     * @throws Exception 抛出异常
     */
    public static void insertOrEditRule(Map<String, Object> map, ResponseBody responseBody) throws Exception{
        OkHttpClient client = new OkHttpClient();
        ObjectMapper objectMapper = new ObjectMapper();
        RequestBody body = RequestBody.create(objectMapper.writeValueAsString(map), MediaType.parse("application/json"));
        if(ObjectUtils.isNotEmpty(responseBody)){
            Request request = new Request.Builder()
                    .url(EmqxConnect.INSTALL_RULE+ "/" +map.get("id"))
                    .put(body)
                    .header("Content-Type", "application/json")
                    .addHeader("Authorization", Credentials.basic(EmqxConnect.apiKey , EmqxConnect.apiSecret))
                    .build();
            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    throw new IOException("Unexpected code " + response);
                }
                System.out.println(response.body().string());
            }
        }else{
            Request request = new Request.Builder()
                    .url(EmqxConnect.INSTALL_RULE)
                    .post(body)
                    .header("Content-Type", "application/json")
                    .addHeader("Authorization", Credentials.basic(EmqxConnect.apiKey , EmqxConnect.apiSecret))
                    .build();
            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    throw new IOException("Unexpected code " + response);
                }
                System.out.println(response.body().string());
            }
        }
    }

    /**
     * 根据id进行查询是否有规则
     * @param ruleCode
     * @throws IOException
     */
    public static ResponseBody getRule(String ruleCode) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(EmqxConnect.GET_RULE+ "/" +ruleCode)
                .get()
                .header("Content-Type", "application/json")
                .addHeader("Authorization",Credentials.basic(EmqxConnect.apiKey , EmqxConnect.apiSecret))
                .build();

        ResponseBody body = null;
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                if(response.code() == 404){
                    body = null;
                }else{
                    throw new IOException("Unexpected code " + response);
                }
            } else if (response.code() == 200) {
                body = response.body();
            }
            return body;
        }
    }

    public static void deleteRules(String rulesCode) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(EmqxConnect.DELETE_RULE_URL+ "/" + rulesCode)
                .delete()
                .header("Content-Type", "application/json")
                .addHeader("Authorization",Credentials.basic(EmqxConnect.apiKey , EmqxConnect.apiSecret))
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            System.out.println(response.body().string());
        }
    }
}